//定义电影演员相关的接口
const express = require('express')
const router = express.Router()
const response = require('../pool/Response')
//引入mysql连接池
const pool = require('../pool/pool')


const joi = require('joi')
const { count, error } = require('console')

//新增电影列表
router.post('/movie-info/add',(req,res) => {
    let {categoryId,cover,title,type,starActor,showingon,score,description,duration} = req.body
    let schema = joi.object({
        categoryId:joi.number().required(),
        cover:joi.string().required(),
        title:joi.string().required(),
        type:joi.string().required(),
        starActor:joi.string().required(),
        showingon:joi.string().required(),
        score:joi.string().required(),
        description:joi.string().required(),
        duration:joi.number().required()
    })
    let {error,value} = schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    pool.query('insert into movie_info (category_id,cover,title,type,star_actor,showingon,score,description,duration) values(?,?,?,?,?,?,?,?,?)',
    [categoryId,cover,title,type,starActor,showingon,score,description,duration],(err,result)=>{
        if(err){
            res.send(response.error(500,err))
            throw err;
        }
        res.send(response.ok())
    })
})


//删除电影
router.post('/movie-info/del',(req,res) => {
    let {id} = req.body
    //表单验证
    let schema = joi.object({
        id:joi.string().required()
    })
    let {error,value} =schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return
    }
    pool.query('delete from movie_info where id = ?',[id],(error,result) => {
        if(error){
            res.send(response.error(500,error))
            throw error;
        }
        res.send(response.ok())
    })
})

/**
 * 查询所有电影类型数据
 */
router.get('/movie-types',(req,res) => {
    pool.query('select * from movie_type',(error,result) => {
        if(error){
            res.send(response.error(500,error))
            throw error;
        }
        res.send(response.ok(result))
    })
})
/**
 * 查询所有电影
 */
router.get('/movie-infos',async (req,res) => {
    let {page,pagesize} = req.query
    let schema = joi.object({
        page:joi.number().required(),
        pagesize:joi.number().integer().max(100).required()
    })
   let {error,value} = schema.validate(req.query)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    //执行查询数组业务
    try{
    let star = (page-1) * pagesize
    let size = parseInt(pagesize)
    let sql = 'select * from movie_info limit ?,?'
    let result = await pool.querySync(sql,[star,size])
    //执行查询总条目数
    let sql2 = 'select count(*) as count from movie_info' 
    let result2 = await pool.querySync(sql2,[star,size])
    let total = result2[0].count
    res.send(response.ok({result,page,pagesize,total}))
    }catch(error){
        res.send(response.error(500,error))
    }
})


/**
 * 通过模糊名称模糊查询电影 
 */
 router.post('/movie-infos/name',async (req,res) => {
    let {name,page,pagesize} = req.body
    let schema = joi.object({
        name:joi.string().required(),
        page:joi.number().required(),
        pagesize:joi.number().integer().max(100).required()
    })
   let {error,value} = schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    //执行查询数组业务
    try{
    let star = (page-1) * pagesize
    let size = parseInt(pagesize)
    let sql = 'select * from movie_info where title like ? limit ?,?'
    let result = await pool.querySync(sql,[`%${name}%`,star,size])
    //执行查询总条目数
    let sql2 = 'select count(*) as count from movie_info where title like ?' 
    let result2 = await pool.querySync(sql2,[`%${name}%`])
    let total = result2[0].count
    res.send(response.ok({result,page,pagesize,total}))
    }catch(error){
        res.send(response.error(500,error))
    }
})


//通过ID查询电影信息
router.get('/movie-info/query',(req,res) => {
    let {id} = req.query
    //表单验证
    let schema = joi.object({
        id:joi.string().required() //必填
    })
    let {error,value} = schema.validate(req.query)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    pool.query('select * from movie_info where id =?',[id],(error,result) => {
        if(error){
            res.send(response.error(500,error))
            throw error
        }
        res.send(response.ok(result[0]))
    })
})

//修改电影接口
router.post('/movie-info/update',(req,res) => {
    let {category_id,cover,title,type,star_actor,showingon,score,description,duration,id} = req.body
    let schema = joi.object({
        category_id:joi.number().required(),
        cover:joi.string().required(),
        title:joi.string().required(),
        type:joi.string().required(),
        star_actor:joi.string().required(),
        showingon:joi.string().required(),
        score:joi.string().required(),
        description:joi.string().required(),
        duration:joi.number().required(),
        id:joi.string().required(),
    })
    let {error,value} = schema.validate(req.body)
    if(error){
        res.send(response.error(400,error))
        return;
    }
    pool.query(
        'update movie_info set category_id=?,cover=?,title=?,type=?,star_actor=?,showingon=?,score=?,description=?,duration=? where id=?',
    [category_id,cover,title,type,star_actor,showingon,score,description,duration,id],(err,result)=>{
        if(err){
            res.send(response.error(500,err))
            throw err;
        }
        res.send(response.ok())
    })
})
//为电影绑定演员接口
router.post('/movie-info/bind-actor',async (req,res) => {
    let {movie_id,actor_ids} = req.body
     let schema = joi.object({
        movie_id:joi.string().required(),
        actor_ids:joi.allow()
     })
     let {error,value} = schema.validate(req.body)
     if(error){
        res.send(response.error(400,error))
         return;
     }
     try{
       let sql = 'delete from movie_info_map_actor where movie_id=?' 
       await pool.querySync(sql,[movie_id])
       if(!actor_ids){
        res.send(response.ok())
        return;
       }
       let params = ''
       let paramsArray = []
       let ids = actor_ids.split(',')
       for(let i=0;i<ids.length;i++){
        params += '(?,?),'
        paramsArray.push(movie_id)
        paramsArray.push(ids[i])
       }
       let sql2 = 'insert into movie_info_map_actor (movie_id,actor_id) values '+params
        sql2 = sql2.substring(0,sql2.length-1)
      let result  = await pool.querySync(sql2,paramsArray)
       res.send(response.ok(result))
    }catch{
        res.send(response.error(500,error))
     }
 
})
module.exports = router